<template>
  <div class="app-container">
    <div class="filter">
      <el-input v-model="filter.username" clearable placeholder="管理员账号" class="filter-input" style="width:200px" @change="getList" />
      <el-input v-model="filter.nickname" clearable placeholder="管理员昵称" class="filter-input" style="width:150px" @change="getList" />
      <el-input v-model="filter.mobile" clearable placeholder="管理员手机号" class="filter-input" style="width:150px" @change="getList" />
      <el-button icon="el-icon-search" type="primary" @click="getList">查询</el-button>
      <el-button icon="el-icon-plus" type="primary" @click="handleCreate">添加</el-button>
    </div>
    <el-table
      ref="adminTable"
      v-loading="loading"
      :data="list"
      row-key="id"
      stripe
      border
      highlight-current-row
      style="width: 100%"
      max-height="750"
    >
      <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" prop="avatar" align="center" width="80">
        <template slot-scope="{row}">
          <img :src="row.avatar" style="width:30px;height:30px;border-radius:5px">
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="username" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" prop="nickname" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机" prop="mobile" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" prop="mobile" align="center">
        <template slot-scope="{row}">
          <el-tag v-for="(role, index) in row.roles" :key="row.id + 'role' + index" type="success" style="margin-left:3px">{{ role.title }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="action" align="center" fixed="right" width="150">
        <template slot-scope="{row}">
          <el-button type="text" icon="el-icon-edit" @click="handleEdit(row)">修改</el-button>
          <el-button v-if="row.id > 1" type="text" style="color: red" icon="el-icon-delete" @click="del(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>1" :total="total" :page.sync="filter.page" :limit.sync="filter.pageSize" @pagination="getList" />

    <el-dialog :visible.sync="dialog" :title="dialogType==='edit'?'修改':'新增管理员'" width="700px">
      <el-form ref="userForm" v-model="temp" :rules="rules" label-position="right" label-width="150px">
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:8000/admin/upload"
            :headers="{ Authorization: 'bearer' + token }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="temp.avatar" :src="temp.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="temp.roles" :disabled="temp.id === 1" style="width:400px" placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="temp.nickname" style="width:400px" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username" :disabled="temp.id" style="width:400px" />
        </el-form-item>
        <el-form-item label="密码" prop="passwrod">
          <el-input v-model="temp.password" :placeholder="temp.id ? '密码为空则不修改' : '请输入密码'" type="password" style="width:400px" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="temp.mobile" style="width:400px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog=false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { adminList, store, update, destroy } from '@/api/permission/admin'
import { roleList } from '@/api/permission/role'
import Pagination from '@/components/Pagination'
import storeToken from '@/store'

export default {
  name: 'PermissionUser',
  components: { Pagination },
  data() {
    return {
      total: 0,
      filter: {
        page: 1,
        pageSize: 20
      },
      list: [],
      roleList: [],
      loading: true,
      dialog: false,
      dialogType: 'create',
      rules: {},
      temp: {},
      token: storeToken.getters.token,
      imageUrl: '',
      acceptImg: ['image/png', 'image/jpg', 'image/jpeg', 'image/gif']
    }
  },
  mounted() {
    this.getList()
    this.getRole()
  },
  methods: {
    // 获取管理员列表
    getList() {
      this.loading = true
      adminList(this.filter).then(res => {
        const { count, list } = res.data
        this.total = count
        this.list = list
        setTimeout(() => {
          this.loading = false
        }, 500)
      })
    },
    // 获取角色列表
    getRole() {
      roleList().then(res => {
        this.roleList = res.data
      })
    },
    // 打开新增管理员窗口
    handleCreate() {
      this.temp = {}
      this.dialogType = 'create'
      this.dialog = true
      this.$nextTick(() => {
        this.$refs['userForm'].clearValidate()
      })
    },
    // 打开修改管理员窗口
    handleEdit(row) {
      this.temp = Object.assign({}, row)
      this.dialogType = 'edit'
      this.dialog = true
      this.temp.roles = row.roles[0].id
      this.$nextTick(() => {
        this.$refs['userForm'].clearValidate()
      })
    },
    // 提交管理员数据（新增或修改）
    save() {
      const tempDate = Object.assign({}, this.temp)
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        // 更新
        update(tempDate, tempDate.id).then(res => {
          this.getList()
          this.dialog = false
          this.$notify({
            title: '修改管理员资料',
            message: res.message,
            type: 'success',
            duration: 2000
          })
        })
      } else {
        // 新增
        store(tempDate).then(res => {
          this.getList()
          this.dialog = false
          this.$notify({
            title: '添加管理员',
            message: res.message,
            type: 'success',
            duration: 2000
          })
        })
      }
    },
    // 删除
    del(id) {
      if (id === 1) {
        this.$message({
          message: '超级管理员无法删除',
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        this.$confirm('是否删除该管理员？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await destroy(id)
          this.getList()
          this.$notify({
            title: '删除管理员',
            message: res.message,
            type: 'success',
            duration: 2000
          })
        })
      }
    },
    // 头像上传成功
    handleAvatarSuccess(res) {
      this.temp.avatar = res.data.url
      this.$forceUpdate()
    },
    // 验证图片上传格式
    beforeAvatarUpload(file) {
      const isJPG = this.checkAvatar(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('头像只允许上传图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 验证图片上传格式
    checkAvatar(type) {
      const accept = this.acceptImg
      for (let i = 0; i < accept.length; i++) {
        if (type === accept[i]) {
          return true
        }
      }
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
  .app-container {
    .filter {
      margin-bottom: 20px;

      .filter-input {
        margin-right: 10px;
      }
    }
  }
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
</style>
